//封装axios工具类
import axios from "axios";
import config from "../config";

//判断环境是生产还是开发
const baseUrl =
  process.env.NODE_ENV === "development"
    ? config.baseUrl.env
    : config.baseUrl.pro;

class HttpRequest {
  constructor(baseUrl) {
    //初始化
    this.baseUrl = baseUrl;
  }
  getInsideConfig() {
    //定义axios相关配置
    const config = {
      baseUrl: this.baseUrl,
      header: {},
    };
    return config;
  }
  interceptors(instance) {
    //拦截器
    instance.interceptors.request.use(
      (config) => {
        console.log("请求拦截器", config);
        return config;
      },
      (error) => {
        console.log("请求拦截器失败", error.message);
        return Promise.reject(error);
      }
    );
    //设置响应拦截器
    instance.interceptors.response.use(
      (response) => {
        console.log("响应拦截器", response);
        return response;
      },
      (error) => {
        console.log("响应拦截器失败", error.message);
        return Promise.reject(error);
      }
    );
  }
  request(options) {
    //接口请求函数
    const instance = axios.create();
    options = { ...this.getInsideConfig(), ...options };
    this.interceptors(instance);
    return instance(options);
  }
}

export default new HttpRequest(baseUrl);
